<template>
	<view class="supermarket">
		<base-navbar back-color="#fff" :title="store_info.name"></base-navbar>
		<view class="wrap">
			<view class="content">
				<view class="header">
					<view class="store">
						<view class="float" style="width: 25%;">
							<image class="logo" :src="store_info.logo" @click="previewImage"></image>
						</view>
						<view class="info float" style="width: 75%;">
							<view class="name" style="height: 28px;">
								<view class="float" style="width: 70%;font-weight: 600;">
									{{ store_info.name }}
								</view>
							</view>
							<view class="desc" style="width: 100%;height: 24px;">
								<view class="tags" v-for="(tags,tindex) in store_info.tags" :key="tindex">
									<!-- <u-tag :text="tags" mode="plain" type="warning" size="mini"></u-tag> -->
								</view>
							</view>
							<view class="address" style="height: 22px;font-size: 10px;">
								<view class="float-item" style="width: 80%;padding: 10px 0px;">
									<view class="float">
										<uni-icons type="location" color="#c5c5c5"></uni-icons>
										<text style="color: #c5c5c5;font-size:10px">距离 {{store_info.distance}} km</text>
									</view>
									<view class="float" style="margin-left: 5px;">
										<uni-icons type="icon-daifukuan" custom-prefix="iconfont"
											color="#c5c5c5"></uni-icons>
										<text style="color: #c5c5c5;font-size:10px">销量 {{store_info.sales_sum}}</text>
									</view>
									<view class="float" style="margin-left: 5px;">
										<uni-icons type="icon-daipingjia" custom-prefix="iconfont"
											color="#c5c5c5"></uni-icons>
										<text style="color: #c5c5c5;font-size:10px">评分 {{store_info.score}}</text>
									</view>
								</view>
								<view class="float-item">
									<image v-if="store_info.business_status == 1"
										:src="imgHost + '/static/images/img-store-status01.png'"></image>
									<image v-else :src="imgHost + '/static/images/img-store-status02.png'"></image>
								</view>
							</view>
						</view>
					</view>
				</view>

				<view>
					<uni-segmented-control :style="'width:' + windowWidth + 'px'" :current="currentTab"
						:values="tabItems" :style-type="styleType" :active-color="themeColor.theme"
						@clickItem="changeTab" />
				</view>

				<view class="cate-wrapper" :style="cateWrapper" v-if="currentTab ==0">
					<scroll-view scroll-y="true" :scroll="scrollStatus" class="left-scroll">
						<view class="field-item" :class="item.id == category_id ? 'active' : ''"
							v-for="(item, index) in category_list" :key="index" @click="changeField(index,item)">
							{{ item.name }}
						</view>
					</scroll-view>
					<scroll-view scroll-y="true" :scroll-top="scroll_top" @scroll="scroll" class="right-scroll"
						@scrolltolower="loadMore">
						<view class="product" v-if="goods_list.length > 0">
							<view class="product-item" style="position:relative;" v-for="(item, index) in goods_list"
								:key="item.id">
								<!-- <view class="product-tag" v-if="item.is_pick" :style="{background: item.is_pick ? '#ff9a04':'#00b01d'}">
									 {{ item.is_pick ? '到店自提' : '' }}
								   </view> -->
								<image @click="goDetail(item.id)" :src="item.logo"
									style="width: 160rpx; height: 160rpx; border-radius: 16rpx;">
								</image>
								<view v-if="item.stock==0" class="no_stock" style="height:95%;width:250rpx;"></view>
								<view class="info">
									<view class="name u-line-1" @click="goDetail(item.id)">
										{{ getGoodsName(item.name) }}
									</view>
									<view class="row" @click="goDetail(item.id)">
										{{item.description || ''}}
									</view>
									<view class="row" @click="goDetail(item.id)">
										月售{{ item.month_sales }}
									</view>
									<view class="row" v-if="item.is_pre_sale==1">
										预售
									</view>
									<view class="other">
										<text class="price" @click="goDetail(item.id)">
											￥{{ item.sale_price }}
											<text class="markete-price">￥{{item.market_price}}</text>
										</text>

										<!-- <u-icon v-if="LoginStatus && store_info.business_status" @click="addCart(item)"
											name="add-fill" custom-prefix="custom-icon" color="#ff7b11" size="42">
										</u-icon> -->
									</view>
								</view>
							</view>
						</view>
						<!-- <u-empty mode="favor" v-if="goods_list.length < 1 && !loading" text="分类下没有商品"></u-empty> -->
						<view v-if="loading" style="margin-left: 45%;margin-top: 50%">
							<!-- <u-loading size="100" mode="flower" /> -->
						</view>
					</scroll-view>
				</view>

				<view class="more-evaluate" v-if="currentTab == 1">
					<view class="more-evaluate">
						<view class="filter">
							<uni-tag text="全部" @click="changeType(0)" :type="type ===0?'error':'default'"></uni-tag>
							<uni-tag text="好评" @click="changeType(1)" :type="type ===1?'error':'default'"></uni-tag>
							<uni-tag text="中评" @click="changeType(2)" :type="type ===2?'error':'default'"></uni-tag>
							<uni-tag text="差评" @click="changeType(3)" :type="type ===3?'error':'default'"></uni-tag>
						</view>
						<c-empty v-if="evaluateList.length < 1" title="还没有评论"></c-empty>
						<evaluate-item :evaluate="item" v-for="(item, index) in evaluateList"
							:key="index"></evaluate-item>
						<!-- <u-loadmore style="margin-bottom: 32rpx" :status="status" /> -->
					</view>
				</view>

				<view class="description" v-if="currentTab == 2">
					<view>店铺名称：{{ store_info.name }}</view>
					<view>店铺地址：{{ store_info.format_address }}</view>
					<view>联系人：{{ store_info.contact_name }}</view>
					<view>电话：{{ store_info.mobile }}</view>
					<view>营业时间：{{ store_info.business_hours }}</view>
					<!-- #ifdef H5 || APP -->
					<view v-html="store_info.description"></view>
					<!-- #endif -->
					<!-- #ifdef MP -->
					<rich-text :nodes="store_info.description"></rich-text>
					<!-- #endif -->
				</view>
			</view>
		</view>
		<view class="tool-bar">
			<view :style="{'backgroundColor': themeColor.theme}" class="cart-bubble active"
				@click="pageTabRoute('/pages/tabbar/index/index')">
				<uni-icons type="home-filled" color="#fff" size="36"></uni-icons>
			</view>
			<view :style="{backgroundColor: themeColor.theme}" class="cart-bubble"
				:class="cartTotalNumber > 0 ? 'active' : ''" @click="cartHandle">
				<uni-badge class="uni-badge-left-margin" :text="cartTotalNumber" absolute="rightTop" :offset="[3, 3]">
					<uni-icons type="cart-filled" color="#fff" size="36"></uni-icons>
				</uni-badge>
			</view>

			<text class="desc" v-if="cartTotalNumber < 1">购物车是空的</text>

			<text class="desc"
				v-if="!cartTotalNumber < 1 && store_info.same_city_delivery && store_info.start_delivery_fee && parseInt(store_info.start_delivery_fee.delivery_fee) > cartData.goods_price">订单金额满
				{{ store_info.start_delivery_fee.delivery_fee }} 配送
			</text>
			<view class="total-price">￥{{ cartData.goods_price }}</view>
			<button :type="cartTotalNumber > 0 ? 'warning' : 'default'" shape="circle" class="buy-btn"
				:disabled="!(cartTotalNumber > 0) || !store_info.business_status" @click="place">
				{{ store_info.business_status ? '去结算' : '商家休息中' }}
			</button>
		</view>

		<!-- 购物车 -->
		<supermarket-cart ref="cartRef" :cartList="cartList" :window-height="windowHeight"
			:cartTotalNumber="cartTotalNumber"></supermarket-cart>
		<!-- <goods-sku ref="skuRef" @submitSukid="add" :goodsInfo="goods" :gspecList="spec" :isBuy=true
			:deliveryType="delivery_type"></goods-sku> -->
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import checkLogin from '@/utils/login';
	import {
		ref,
		reactive,
		toRefs,
		inject,
		computed,
		onMounted,
	} from 'vue';
	import {
		onLoad,
		onShow,
		onReady,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';

	const imgHost = inject('web_host');

	const cartRef = ref(null);
	const skuRef = ref(null);

	const state = reactive({
		themeColor: JSON.parse(cache.get('themeColor')),
		store_info: {},
		tabItems: ['商品', '评论', '商家信息'],
		styleType: 'text',
		windowWidth: '390',
		currentTab: 0,
		category_list: [],
		goods_list: [],
		goods_id: 0,
		page: 0,
		total_page: 0,
		windowHeight: 0,
		cartTotalNumber: 0,
		loading: false,
		more: false,
		type: 0,
		evaluateList: [],
		load_status: 'loadmore',
		cartData: {
			goods_price: '0',
		},
		cartList: [],
		cateWrapper: {},
		scrollStatus: false,
		statusBarHeight: 0,
		scroll_top: 0,
		category_id: 0,
		//防抖设置
		old: {
			scrollTop: 0
		},
	});

	onLoad((opt) => {
		if (opt.hasOwnProperty('store_id')) {
			getStoreInfo(opt.store_id);
			getComment();
		}
	});

	onShow(() => {});

	onMounted(() => {
		// 获取当前系统的信息
		const sysInfo = uni.getSystemInfoSync();
		console.log("获取当前系统的信息", sysInfo);
		// 为 wh 窗口可用宽度动态赋值
		state.windowWidth = sysInfo.windowWidth;
		console.log("窗口可用宽度", state.windowWidth);
	});

	onReady(() => {
		uni.getSystemInfo({
			success: result => {
				state.windowHeight = result.windowHeight * 0.5
			}
		})
	});

	onPullDownRefresh((e) => {
		console.log("下拉刷新", e);
	});

	onReachBottom((e) => {
		console.log("上拉加载更多", e);
	});

	function getStoreInfo(store_id) {
		request.get('store/info', {
			id: store_id,
			longitude: cache.get('longitude'),
			latitude: cache.get('latitude'),
		}).then(res => {
			console.log('Store', res);
			if (res.code == 1) {
				state.store_info = res.data;

				getCategory();
			} else {
				uni.showModal({
					title: '错误',
					content: '商家不存在',
					showCancel: false,
					confirmText: '返回',
					success: function(res) {
						uni.navigateBack();
					}
				});
			}
		})
	}

	function getComment() {
		state.status = 'loading'

		request.get('comment/list', {
			store_id: state.store_info.id,
			type: state.type,
			skip: state.evaluateList.length,
			goods_id: state.goods_id
		}).then(res => {
			if (res.code === 1) {
				state.loading = false;
				if (res.data.list) {
					if (state.evaluateList.length > 0) {
						state.evaluateList = state.evaluateList.concat(res.data.list);
					} else {
						state.evaluateList = res.data.list;
					}
				}
				state.more = res.data.more
				if (res.data.more) {
					state.status = 'loadmore'
				} else {
					state.status = 'nomore'
				}
			}
		})
	}

	function changeTab(e) {
		console.log('changeTab', e);
		console.log(e);
		state.currentTab = e.currentIndex;
		console.log("当前选中", state.currentTab);
	}

	function cartHandle() {
		cartRef.value.open();
	}

	function skuHandle() {
		skuRef.value.open();
	}

	function stickyHandle() {
		// #ifdef APP-PLUS || MP
		state.cateWrapper = Object.assign(state.cateWrapper, {
			paddingTop: (state.statusBarHeight) + 'rpx'
		})
		// #endif
		// #ifdef H5
		state.cateWrapper = Object.assign(state.cateWrapper, {
			paddingTop: '96rpx'
		})
		// #endif
		state.scrollStatus = true
	}

	function unStickyHandle() {
		//每次点击回到顶部
		state.scroll_top = state.old.scrollTop
		// this.$nextTick(function() {
		// 	this.scroll_top = 0
		// });
		state.scrollStatus = false
		setHeight()
	}

	//获取屏幕高度并获取状态栏高度
	function setHeight() {
		uni.getSystemInfo({
			success: res => {
				// #ifdef APP-PLUS
				state.statusBarHeight = (res.statusBarHeight * 2) + 80
				// #endif
				state.cateWrapper = {
					minHeight: (res.windowHeight - 49) + 'px'
				}
			}
		})
	}

	function previewImage() {
		// 使用uni.previewImage预览图片
		uni.previewImage({
			current: 0,
			urls: [
				state.store_info.logo
			]
		});
	}

	function loadMore() {
		//判断当前目录的页码是否加载完
		if (this.page < this.total_page) {
			this.load_status = 'loading'
			for (let i = 0; i < this.category_list.length; i++) {
				if (this.category_list[i].id === this.category_id) {
					this.currentIndex = i
				}
			}
			//单页加载完后页数加一
			this.page++;
			this.getGoodsInfo(this.category_list[this.currentIndex].id, true)
		}
	}

	function getCategory() {
		request.get('product/categoryList', {
			store_id: state.store_info.id
		}).then(res => {
			console.log("店铺产品分类", res);
			if (res.code == 1) {
				state.category_list = res.data
				if (res.data.length < 1) {
					state.category_list = [{
						'name': '推荐',
						'id': '0'
					}]
				}
				if (res.data.length > 0) { // 如果没有分类，就不显示商品列表,之前一直转圈报错
					state.category_id = res.data[0].id
					getGoodsInfo(res.data[0].id)
				} else {
					state.loading = false
					state.load_status = "nomore"
				}
			}
		})
	}

	function getGoodsInfo(category_id, loadmore = false) {
		request.get('product/productList', {
			category_id: category_id,
			goods_id: state.goods_id,
			page: state.page,
		}).then(res => {
			console.log("产品列表", res);
			if (!res.data) {
				state.goods_list = []
			}
			if (res.code == 1) {
				if (loadmore) {
					state.goods_list = state.goods_list.concat(res.data)
					state.total_page = res.total_page
					if (state.page < state.total_page) {
						state.load_status = "loadmore"
					} else {
						state.load_status = "nomore"
					}
				} else {
					//单页加载完后页数加一
					state.page++;
					state.goods_list = res.data
					state.loading = false
					state.total_page = res.total_page
					if (state.page < state.total_page) {
						state.load_status = "loadmore"
					} else {
						state.load_status = "nomore"
					}
				}
			} else {
				state.loading = false
			}
		})
	}

	function getGoodsName(name) {
		if (name.length > 20) {
			name = name.substr(0, 20) + "...";
		}
		return name;
	}

	function changeField(index, item) {
		this.currentIndex = index
		this.category_id = item.id

		//每次点击侧边栏重置页数
		this.page = 0;

		//每次点击回到顶部
		this.scroll_top = this.old.scrollTop
		this.$nextTick(function() {
			this.scroll_top = 0
		});

		//清空商品列表
		this.goods_list = [];

		//显示加载动画
		this.loading = true;
		this.getGoodsInfo(item.id);
		setTimeout(() => {

		}, 500)
	}

	function goDetail(id) {
		pageRoute('/pages/product/product-detail/product-detail?goods_id=' + id);
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	};

	function pageTabRoute(url) {
		uni.switchTab({
			url
		});
	};

	const {
		themeColor,
		store_info,
		tabItems,
		styleType,
		windowWidth,
		currentTab,
		category_list,
		goods_list,
		goods_id,
		page,
		total_page,
		windowHeight,
		cartTotalNumber,
		loading,
		more,
		type,
		evaluateList,
		load_status,
		cartData,
		cartList,
		cateWrapper,
		scrollStatus,
		statusBarHeight,
		scroll_top,
		category_id,
		old,
	} = toRefs(state);
</script>

<style lang="scss">
	.supermarket {
		height: 100%;

		.wrap {
			padding: $m24 0;
			// height: calc(100% - 340rpx + 120rpx);
			height: 98%;
			margin-top: -20rpx;

			.swiperImg {
				height: 276rpx;
				width: 100%;
			}

			.content {
				height: 100%;
				display: flex;
				flex-direction: column;
				background-color: #fff;
				border-radius: $radius-12;

				.header {
					padding: $m24;

					.store {
						@include f-between;
						align-items: flex-end;

						.logo {
							width: 180rpx;
							height: 190rpx;
							border-radius: $radius-12;
						}

						.info {
							flex: 1;
							margin-left: $m24;

							.name {
								font-size: $font-32;
								// font-weight: bold;
							}

							.u-line-1 {
								word-break: break-all;
								text-overflow: ellipsis;
								display: -webkit-box;
								-webkit-box-orient: vertical;
								-webkit-line-clamp: 2;
								overflow: hidden;
							}

							.desc {
								font-size: $font-24;
								color: $u-tips-color;
							}

							.address {
								font-size: $font-24;
								color: $u-tips-color;

								.float-item {
									float: left;

									.float {
										float: left;
									}

									image {
										width: 50px;
										height: 50px;
									}
								}
							}
						}
					}

					.discount {
						display: flex;
						align-items: center;
						padding: $m12 0;
						color: $u-type-warning;
						font-size: $font-24;

						.label {
							position: relative;
							margin-right: $m16;
							padding: 0.3em 0.6em;
							background-color: $u-type-warning;
							color: $u-reverse-color;
							font-size: $font-24;
							border-radius: $radius-8;

							&::after {
								position: absolute;
								top: 50%;
								right: -10rpx;
								content: '';
								width: 20rpx;
								height: 20rpx;
								background-color: $u-bg-reverse-color;
								border-radius: $radius-circle;
								transform: translateY(-50%);
							}
						}
					}
				}

				.cate-wrapper {
					display: flex;
					flex: 1;
					overflow: hidden;
					border-top: 1rpx solid #f3f4f6;
					padding-bottom: calc(98rpx + 16rpx);

					.left-scroll,
					.right-scroll {
						height: 100%;
					}

					.left-scroll {
						width: 180rpx;
						background-color: $u-bg-color;
						overflow: hidden;

						.field-item {
							position: relative;
							// height: 104rpx;
							padding: 20rpx 5rpx;
							display: flex;
							text-align: center;
							justify-content: center;
							align-items: center;
							color: $u-main-color;
							font-size: 24rpx;

							&.active {
								background-color: $u-bg-reverse-color;
								font-size: 24rpx;

								&::before {
									position: absolute;
									left: -4rpx;
									top: 50%;
									width: 8rpx;
									height: 50%;
									content: '';
									background-color: $u-type-warning;
									border-radius: $radius-8;
									transform: translateY(-50%);
								}
							}
						}
					}

					.right-scroll {
						flex: 1;
						overflow: hidden;
						background-color: #fff;

						.product {
							padding: 0 $m24;

							.product-item {
								@include f-between;
								flex-direction: row;
								padding: $m20 0;
								align-items: flex-start;

								.product-tag {
									z-index: 888;
									position: absolute;

									font-size: 22rpx;
									color: #fff;
									padding: 3rpx 10rpx;
									border-radius: 0rpx 0rpx 20rpx 0rpx;
								}

								.info {
									overflow: hidden;
									position: relative;
									flex: 1;
									height: 170rpx;
									margin-left: $m24;

									.name {
										color: $u-main-color;
										font-weight: bold;
									}

									.row {
										font-size: $font-24;
										color: $u-tips-color;
									}

									.other {
										position: absolute;
										bottom: 0;
										width: 100%;
										@include f-between;

										.price {
											color: $u-type-error;
											font-size: $font-36;
											font-weight: bold;

										}

										.markete-price {
											margin-left: $m12;
											text-decoration: line-through;
											font-size: $font-24;
											color: $u-tips-color;
										}

										.u-btn {
											margin: 0;
										}

										.action-btns {
											display: flex;
											align-items: center;

											.count {
												margin: 0 $m8;
											}
										}
									}
								}
							}
						}
					}
				}

				.more-evaluate {
					border-top: 1rpx solid #f3f4f6;
					padding-bottom: calc(98rpx + 16rpx);
					background-color: $u-bg-reverse-color;

					.filter {
						padding: $m32 $m32 $m16;

						.u-tag {
							margin-right: $m24;
						}
					}
				}

				.description {
					border-top: 1rpx solid #f3f4f6;
					padding: $m24;
					font-size: $font-28;
					padding-bottom: calc(98rpx + 16rpx);
				}
			}
		}

		.tool-bar {
			@include f-between;
			position: fixed;
			z-index: 20000;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 98rpx;
			padding: 0 $m20;
			background-color: $u-bg-reverse-color;
			border-top: 1px solid $u-border-color;

			.cart-bubble {
				position: relative;
				@include f-center;
				width: 86rpx;
				height: 86rpx;
				border-radius: $radius-circle;
				margin-right: 20rpx;

				&.active {
					background-color: $u-type-warning;

					.u-icon {
						color: $u-reverse-color !important;
					}
				}
			}

			.desc {
				margin-left: $m16;
			}

			.total-price {
				flex: 1;
				margin: 0 $m24;
				text-align: right;
				font-size: $font-36;
			}

			.buy-btn {
				margin-right: $m40;
			}
		}
	}
</style>